package cn.wangzg.course0602;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.wangzg.course0602.util.HttpUtil;

public class MainActivity extends AppCompatActivity {
//    private Handler handler=new Handler(){
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            String str= (String) msg.obj;
//            tv_html.setText(str);
//        }
//    };
    private TextView tv_html;
    //官方建议写法
    static class MyHandler extends Handler {
        // WeakReference to the outer class's instance.
        private WeakReference<MainActivity> mOuter;

        public MyHandler(MainActivity activity) {
            mOuter = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity outer = mOuter.get();
            if (outer != null) {
                if(msg.what==1) {
                    String str = (String) msg.obj;
                    outer.tv_html.setText(str);
                }
            }
        }
    }
    private MyHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler=new MyHandler(this);
        //main thread
        //局部转全局  Ctrl+alt+F    full
        tv_html = findViewById(R.id.tv_html);
        //3.网络访问是耗时操作，需要在新线程中进行
        new Thread(){//new thread
            @Override
            public void run() {
                String strUrl = "http://www.zzuli.edu.cn/";
                String s = HttpUtil.doGet(strUrl);
                //System.out.println(s);
                //tv_html.setText(s);
                Message msg=new Message();
                msg.what=1;//区分不同的返回值
                msg.obj=s;
                handler.sendMessage(msg);
            }
        }.start();

    }

}
